package com.rent.collectrent.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rent.collectrent.dto.WriteOffRequest;
import com.rent.collectrent.dto.WriteOffResponse;
import com.rent.collectrent.entity.WriteOffDetail;
import com.rent.collectrent.entity.WriteOffSummary;
import com.rent.collectrent.mapper.WriteOffDetailMapper;
import com.rent.collectrent.mapper.WriteOffSummaryMapper;
import com.rent.collectrent.service.RentWriteOffService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author news
 * *@date 2025/9/28
 */
@RestController
@RequestMapping("/api/write-off")
@Api(tags = "租金核销管理")
@Slf4j
public class WriteOffController {
    @Autowired
    private RentWriteOffService writeOffService;
    @Autowired
    private WriteOffSummaryMapper writeOffSummaryMapper;
    @Autowired
    private WriteOffDetailMapper writeOffDetailMapper;

    @PostMapping("/batch")
    @ApiOperation("发起批量核销")
    public ResponseEntity<WriteOffResponse> startBatchWriteOff(@RequestBody WriteOffRequest request) {

        log.info("接收到批量核销请求: {}", request);

        try {
            CompletableFuture<WriteOffResponse> future = writeOffService.batchWriteOff(request);

            // 非阻塞方式，立即返回批次号
            WriteOffResponse immediateResponse = WriteOffResponse.builder()
                    .batchNo(future.get().getBatchNo())
                    .status("PROCESSING")
                    .message("核销任务已提交，请使用批次号查询进度")
                    .build();

            return ResponseEntity.ok(immediateResponse);

        } catch (Exception e) {
            log.error("批量核销异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(writeOffService.buildErrorResponse(e.getMessage()));
        }
    }

    @GetMapping("/progress/{batchNo}")
    @ApiOperation("查询核销进度")
    public ResponseEntity<WriteOffSummary> getWriteOffProgress(
            @PathVariable String batchNo) {

        WriteOffSummary summary = writeOffSummaryMapper.selectOne(
                new QueryWrapper<WriteOffSummary>().eq("batch_no", batchNo));

        if (summary == null) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(summary);
    }

    @GetMapping("/details/{batchNo}")
    @ApiOperation("查询核销明细")
    public ResponseEntity<List<WriteOffDetail>> getWriteOffDetails(@PathVariable String batchNo) {

        List<WriteOffDetail> details = writeOffDetailMapper.selectList(
                new QueryWrapper<WriteOffDetail>().eq("batch_no", batchNo));

        return ResponseEntity.ok(details);
    }

}
